import os

class Load_HEX:
    def __init__(self):
        self.data = None

    def load_file(self, file_path):
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        with open(file_path, 'r') as f:
            content = f.read().strip()
        
        first_char = content[0].upper()
        
        if first_char == 'S':
            self.data = self._parse_srec(content)
        elif first_char == ':':
            self.data = self._parse_intel_hex(content)
        else:
            raise ValueError("不支持的文件格式")

    def _parse_srec(self, content):
        segments = []
        current_segment = None
        lines = content.strip().split('\n')
        for line in lines:
            if not line.startswith('S'):
                continue
            record_type = line[1]
            if record_type in ['1', '2', '3']:
                byte_count = int(line[2:4], 16)
                address = int(line[4:8], 16) if record_type == '1' else int(line[4:10], 16) if record_type == '2' else int(line[4:12], 16)
                data = line[8:-2] if record_type == '1' else line[10:-2] if record_type == '2' else line[12:-2]
                data_bytes = bytes.fromhex(data)
                
                if current_segment is None or address != current_segment['start_address'] + len(current_segment['data']):
                    if current_segment:
                        segments.append(current_segment)
                    current_segment = {
                        'start_address': address,
                        'length': 0,
                        'data': []
                    }
                
                current_segment['data'].extend(data_bytes)
                current_segment['length'] += len(data_bytes)
        
        if current_segment:
            segments.append(current_segment)
        
        return segments

    def _parse_intel_hex(self, content):
        segments = []
        current_segment = None
        base_address = 0
        next_expected_address = None
        lines = content.strip().split('\n')
        for line in lines:
            if not line.startswith(':'):
                continue
            byte_count = int(line[1:3], 16)
            address = int(line[3:7], 16)
            record_type = int(line[7:9], 16)
            data = line[9:-2]
            
            if record_type == 0:  # 数据记录
                data_bytes = bytes.fromhex(data)
                full_address = base_address + address
                
                if next_expected_address is not None and full_address != next_expected_address:
                    if current_segment:
                        segments.append(current_segment)
                    current_segment = None
                
                if current_segment is None:
                    current_segment = {
                        'start_address': full_address,
                        'length': 0,
                        'data': []
                    }
                
                current_segment['data'].extend(data_bytes)
                current_segment['length'] += len(data_bytes)
                next_expected_address = full_address + len(data_bytes)
            elif record_type == 1:  # 文件结束记录
                # 文件结束记录，不需要处理
                pass
            elif record_type == 2:  # 扩展段地址记录
                base_address = int(data, 16) << 4
            elif record_type == 3:  # 开始段地址记录
                # 这个记录通常不需要处理，因为它主要用于16位架构
                pass
            elif record_type == 4:  # 扩展线性地址记录
                base_address = int(data, 16) << 16
            elif record_type == 5:  # 开始线性地址记录
                # 这个记录设置程序的入口点，通常不需要在数据处理中使用
                pass
        
        if current_segment:
            segments.append(current_segment)
        
        return segments

    def get_data(self):
        return self.data

# 使用示例
if __name__ == "__main__":
    hex_loader = Load_HEX()
    try:
        hex_loader.load_file("flash_image_20210104.hex")
        data = hex_loader.get_data()
        print("成功加载并解析HEX文件")
    except Exception as e:
        print(f"错误: {str(e)}")
